package com.first.xiinn.action.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import nl.captcha.Captcha;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.net.URLCodec;
import org.apache.log4j.Logger;
import org.springframework.mail.MailException;

import com.first.core.Constants;
import com.first.core.common.QueryFilter;
import com.first.core.util.MailEngine;
import com.first.core.util.RequestUtil;
import com.first.core.util.StringUtil;
import com.first.core.util.UUID;
import com.first.core.web.action.BaseAction;
import com.first.xiinn.model.User;
import com.first.xiinn.service.UserService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class UserAction extends BaseAction {

	Logger log = Logger.getLogger(UserAction.class);
	//邮箱已验证标记
	private final static String validated_yes = "1";
	@Resource
	private UserService userService;
	@Resource
	private MailEngine mailEngine;
	private User user;

	private String userName;
	
	private String password;

	private String query;
	
	private String data;
	
	private String id;
	//验证码
	private String checkCode;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public String getCheckCode() {
		return checkCode;
	}

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	/**
	 * 用户登陆
	 * 
	 * @return
	 */
	public String login() {
		User loginUser = null;
		HttpServletRequest req = getRequest();

		loginUser = userService.getUser(userName);
		if (null == loginUser) {
			req.setAttribute("errorMsg", "用户信息不存在，请重新输入！");
			return "login";// 用户不存在
		}

		if (loginUser.getPassword().equals(StringUtil.encryptSha256(password))) {
			HttpSession session = getSession();
			session.setAttribute("member", loginUser);
		} else {
			req.setAttribute("errorMsg", "用户信息不存在或密码错误，请重新输入！");
			return "login";// 用户密码错误
		}

		return SUCCESS;
	}

	public String forgotten() {
		HttpServletRequest r = getRequest();
		HttpSession session = r.getSession();
		String name = r.getParameter("name");
		String email = r.getParameter("email");
		if (name == null || name.equals("") || email == null
				|| email.equals("")) {
			session.setAttribute("ERROR", "用户名或邮箱不能为空!");
			return SUCCESS;
		} else {
			List list = userService.getforgotten(name, email);
			if (list.isEmpty()) {
				session.setAttribute("ERROR", "验证错误!");
			} else {
				session.setAttribute("ERROR", "验证正确!");
			}
			return SUCCESS;
		}
	}

	/**
	 * 模糊查询作者
	 * 
	 * @return
	 */
	public String searchAutor() {
		List list = this.userService.searchAutor(query);
		Gson gson = new Gson();
		StringBuffer sb = new StringBuffer("{totalCount:123,result:");
		sb.append(gson.toJson(list));
		sb.append("}");
		setJsonString(sb.toString());
		return "success";
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	/**
	 * 验证邮箱是否已经使用
	 * 
	 * @return
	 */
	public String checkEmail(){
		PrintWriter pw = null;
		try{
			pw = getResponse().getWriter();
			User user = userService.ibGetUserByEmail(this.user.getEmail());
			if(user != null && !"".equals(user.getEmail())){
				pw.write("true");
			}else{
				pw.write("false");
			}
		}catch (IOException e) {
			e.printStackTrace();
			if(pw != null){
				pw.write("error");
			}
			log.error(e.getMessage());
		}
		if(pw != null){
			pw.close();
		}
		return null;
	}
	
	
	/**
	 * 验证图片验证码是否正确
	 * 
	 * @return
	 */
	public String checkCaptcha(){
		PrintWriter pw = null;
		try{
			pw = getResponse().getWriter();
			//从session中获取已生成的验证码
			Captcha c = (Captcha) getSession().getAttribute(Constants.CAPTCHA_KEY);
			String sessionCode = "";
			if(c != null){
				sessionCode = c.getAnswer();
			}
			if(checkCode != null && sessionCode.equals(checkCode)){
				pw.write("true");
			}else{
				pw.write("false");
			}
		}catch (IOException e) {
			e.printStackTrace();
			if(pw != null){
				pw.write("error");
			}
			log.error(e.getMessage());
		}
		if(pw != null){
			pw.close();
		}
		return null;
	}
	
	/**
	 * 前台会员注册
	 * @return
	 */
	public String register() {
		User u = new User();
		u.setId(UUID.getUUID());
		u.setEmail(user.getEmail());
		u.setPassword(StringUtil.encryptSha256(user.getPassword()));
		u.setIsValidated("0");//默认为未通过邮箱验证
		
		// 获得域名
		String url = RequestUtil.getAppURL(getRequest());
		
		try{
			userService.registerUser(u, url);
		}catch (Exception e) {
			log.error(e.getMessage());
		}
		
		return SUCCESS;
	}
	
	/**
	 * 激活邮箱
	 * @return
	 * @throws IOException
	 */
	public String verifyInfo() throws IOException {
		if (data == null) {
			return ERROR;
		}
		if (data.equals("") || data.length() == 0) {
			return ERROR;
		}
		try {
			byte[] username = getRequest().getParameter("data").getBytes();
			username = Base64.decodeBase64(username);
			byte[] userNameAfterDecode = new URLCodec().decode(username);
			String userName = new String(userNameAfterDecode);

			String[] code = userName.split("\\+");
			User user = userService.ibGetUserByVerifyData(code[1]);
			if (user == null) {
				message = "邮箱激活失败，验证链接信息有误！请尝试重发激活邮件";
				return ERROR;
			} else {
				User userInfo = userService.ibGet(code[0]);
				if (userInfo == null) {
					message = "邮箱激活失败,验证链接信息有误！请尝试重发激活邮件";
					return ERROR;
				}
				if (validated_yes.equals(userInfo.getIsValidated())) {
					message = "邮箱激活失败,邮箱已激活，无需多次激活！";
					return ERROR;
				} else {
					userInfo.setIsValidated(validated_yes);
					userService.ibSave(user);//保存并更新 TODO 带将save与update接口区分后，单独使用update接口
					//获取域名
					String url = RequestUtil.getAppURL(getRequest());
					
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("user", user);
					map.put("url", url);
					try {
						mailEngine.sendMessage(user.getEmail(),
								"“习嬴网”-您的注册邮箱已确认激活",
								"email-template/user_verify_success_mail.vm",
								map);
					} catch (MailException me) {
						log.error("verifyInfo", me);
					}

					message = "邮箱激活成功";
					return SUCCESS;
				}
			}
		} catch (Exception e) {
			message = "邮箱激活失败";
			return ERROR;
		}
	}
	
	public String list()
    {
        QueryFilter filter = new QueryFilter(getRequest());
        List<User> list = this.userService.getAll(filter);

        Type type = new TypeToken<List<User>>(){}.getType();
        StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
          .append(filter.getPagingBean().getTotalItems()).append(",result:");
        Gson gson = new Gson();
        buff.append(gson.toJson(list, type));
        buff.append("}");
        this.jsonString = buff.toString();
        System.out.println("=========="+jsonString);
        
        return "success";
    }
	
	  public String get()
	  {
	    User user = (User)this.userService.get(this.id);
	    Gson gson = new Gson();

	    StringBuffer sb = new StringBuffer("{success:true,data:");
	    sb.append(gson.toJson(user));
	    sb.append("}");
	    setJsonString(sb.toString());

	    return "success";
	  }
	  
	  public String save()
	  {
		  if(user.getId().equals("")){
			   user.setId(null);
	        }
		    userService.save(this.user);
	        if(user != null){
	            setJsonString("{success:true}");
	        } else{
	            setJsonString("{success:false}");
	        }
	        return "success";
	  }
	
}
